<template>
  <div>
    <div class="xq-form-wrapper">
      <a-spin :spinning="spinning" class="xq-form-content">
        <TableBody
          selectHead
          selection
          tableName="checkCard"
          :selectedRowKeys.sync="selectedRowKeys"
          :source="tableData"
          :headerRowID="'sortable_list'"
          :columns="columns"
          @onReload="onGetCheckCardList"
          @onExport="() => download(1)"
          @onExportAll="() => download(2)"
          ><template slot="search">
            <a-month-picker v-model="time" style="width: 180px" placeholder="选择月份" :allow-clear="false" @change="monthChange" />
            <a-input-search
              v-model="searchForm.empInfoName"
              allow-clear
              placeholder="搜索员工"
              style="width: 180px"
              @change="handleSearch"
            />
            <a-tree-select
              style="width: 180px"
              placeholder="请选择岗位"
              :tree-data="depInfoOptions"
              allow-clear
              v-model="positionInfoIdArr"
              @change="handleDepChange"
            />
          </template>
          <template slot-scope="prop">
            <XqTable
              :class="prop.className"
              :components="prop.components"
              :columns="prop.columns"
              :scroll="{ x: prop.scrollWidth }"
              :customHeaderRow="
                () => {
                  return {
                    domProps: {
                      id: prop.headerRowID
                    }
                  };
                }
              "
              :customize="FormJson['config']['table']['customize']"
              :pagination="false"
              :dataSource="tableData"
              :rowSelection="
                FormJson['config']['table']['extend']['batch']
                  ? {
                      selectedRowKeys: selectedRowKeys,
                      onChange: onSelectChange
                    }
                  : null
              "
              class="xq-form-content-table"
            >
              <template v-for="(col, index) in columns" v-slot:[`xq_${col.dataIndex}`]>
                <span :key="index">
                  {{ col.customTitle }}
                </span>
              </template>
              <!-- eslint-disable-next-line prettier/prettier -->
              <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
                <!-- <span v-if="col.dataIndex === 'gmtCreate'" :key="index">
              {{ moment(text).format("YYYY/MM/DD") }}
            </span> -->
                <span
                  v-if="col.dataIndex === 'shouldDayCount' || col.dataIndex === 'normalDay' || col.dataIndex === 'unusualDay'"
                  :key="index"
                >
                  <span>{{ text ? text + "天" : "--" }}</span>
                </span>
                <span v-else-if="col.dataIndex === 'workDate'" :key="index">
                  <span>{{ text || "--" }}</span>
                </span>
                <span v-else-if="col.dataIndex === 'beLateTime' || col.dataIndex === 'leaveEarlyTime'" :key="index">
                  <span>{{ text ? text + "分钟" : "--" }}</span>
                </span>
                <span
                  v-else-if="
                    col.dataIndex === 'unusualCount' ||
                      col.dataIndex === 'beLateCount' ||
                      col.dataIndex === 'leaveEarlyCount' ||
                      col.dataIndex === 'lackCount'
                  "
                  :key="index"
                >
                  <span>{{ text ? text + "次" : "--" }}</span>
                </span>
                <span v-else-if="col.dataIndex === 'tableAction'" :key="index">
                  <a @click="() => enterDetail(record)">详情</a>
                </span>
                <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" />
              </template>
            </XqTable>
          </template>
        </TableBody>
        <div class="xq-form-content-pagination" style="margin-bottom: 24px">
          <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
          <a-pagination
            v-model="pageNo"
            :page-size="pageSize"
            :total="total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :page-size-options="['10', '20', '50', '100']"
            @change="onPageChange"
            @showSizeChange="onPageSizeChange"
          />
        </div>
      </a-spin>
    </div>
    <select-export :visible.sync="visible" @changeSE="changeSE" />
  </div>
</template>

<script>
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";

const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});

import { checkMonth } from "./api";
import { getPositionInTree } from "@/api/department/position";
import moment from "moment";
import axios from "axios";
import qs from "qs";
import selectExport from "../../component/select-export";
export default {
  mixins: [curdMixin],
  components: {
    selectExport
  },
  data() {
    return {
      visible: false,
      spinning: false,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      companyId: "",
      searchForm: {
        year: moment().format("YYYY"),
        month: moment().format("MM"),
        companyId: "",
        positionInfoId: "",
        empInfoName: ""
      },
      depInfoOptions: [],
      time: moment().format("YYYY-MM"),
      entityCount: 0,
      positionInfoIdArr: []
    };
  },

  created() {
    this.searchForm.companyId = this.$store.state.hr.companyId;
    this.companyId = this.$store.state.hr.companyId;
    getPositionInTree({ companyId: this.companyId }).then(res => {
      this.depInfoOptions = this.tree1(res.data[0].positionChildList, "positionChildList", true);
    });
    this.onGetCheckCardList();
  },

  methods: {
    handleSearch() {
      this.pageNo = 1;
      this.onGetCheckCardList();
    },
    handleDepChange(id) {
      this.searchForm.positionInfoId = id;
      this.pageNo = 1;
      this.onGetCheckCardList();
    },
    async onGetCheckCardList() {
      try {
        this.spinning = true;
        const { data } = await checkMonth({
          ...this.searchForm,
          pageNo: this.pageNo,
          pageSize: this.pageSize
        });
        this.tableData = data.entities;
        this.total = data.entityCount;
        setTimeout(() => (this.spinning = false), 500);
      } catch (err) {
        console.log("error log --> ", err);
        setTimeout(() => (this.spinning = false), 500);
      }
    },
    onPageChange(page) {
      this.pageNo = page;
      this.onGetCheckCardList();
    },
    onPageSizeChange(current, pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.onGetCheckCardList();
    },
    enterDetail(record) {
      const { empInfoId, empInfoName } = record;
      this.$router.push({
        path: "/check/checkCard/cardDetail",
        query: {
          empInfoId,
          empInfoName,
          year: this.searchForm.year,
          month: this.searchForm.month
        }
      });
    },
    monthChange(date, dateString) {
      this.pageNo = 1;
      this.searchForm.year = moment(dateString).format("YYYY");
      this.searchForm.month = moment(dateString).format("MM");
      this.time = moment(dateString).format("YYYY-MM");
      this.onGetCheckCardList();
    },
    // 导出员工信息excel表
    download(i) {
      const token = this.$store.state.auth.token;
      let params = {};
      if (i === 2) {
        params = {
          ...this.searchForm
        };
      } else {
        params = {
          companyId: this.searchForm.companyId,
          positionInfoId: this.searchForm.positionInfoId,
          year: this.searchForm.year,
          month: this.searchForm.month,
          empInfoIdList: this.selectedRowKeys
        };
      }
      axios({
        url: `/hr/api/v1/attendPunchRecords/exportAttendPunchRecord`,
        params,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", `${this.$store.state.hr.companyName}_` + "考勤打卡报表" + ".xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("error log --> ", err);
        });
    },

    tree1(array, childKey, onlyLastChild) {
      if (array === null || array.length < 1) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id;
        item["key"] = item.id;
        item["label"] = item.name;
        item["children"] = item[childKey];

        if (item.children) {
          // item["selectable"] = false;
          // item["selectable"] = false;
          this.tree1(item.children, childKey, onlyLastChild);
        }
      });
      return array;
    },
    onShow(e) {
      this.visible = true;
      this.btnType = e;
    },
    changeSE(e) {
      if (e === 1) {
        this.download(this.btnType);
      }
      if (e === 2) {
        this.download(this.btnType);
      }
    }
  }
};
</script>

<style lang="scss" scoped></style>
